﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Tracker.Data.Repository;
using Tracker.Data.UnitOfWork;
using Tracker.Domain.Entities;

namespace Tracker.Services.Implementation
{
    public class Service<T> where T : BaseEntity
    {
        protected IRepository<T> Repository { get; private set; }

        private readonly IUnitOfWork _unitOfWork;

        public Service(IRepository<T> repository,
                       IUnitOfWork unitOfWork)
        {
            Repository = repository;
            _unitOfWork = unitOfWork;
        }

        protected T Single(Expression<Func<T, bool>> predicate)
        {
            return Repository.Get(predicate);
        }

        protected IList<T> All()
        {
            return Repository.GetAll();
        }

        protected IList<T> All(Expression<Func<T, bool>> predicate)
        {
            return Repository.GetAll(predicate);
        }

        protected int Add(T entity)
        {
            Repository.Add(entity);
            Save();
            return entity.ID;
        }

        public void Delete(int id)
        {
            Repository.Delete(id);
            Save();
        }

        protected void Save()
        {
            _unitOfWork.Commit();
        }
    }
}
